from openai import OpenAI
from typing import List, Dict, Any
import json
import os
from langchain_community.vectorstores import Chroma
from langchain_ollama import OllamaEmbeddings
from dotenv import load_dotenv

load_dotenv()

class RAGProcessor:
    def __init__(self):
        self.client = OpenAI(
            base_url=os.getenv("LLM_BASE_URL"),
            api_key=os.getenv("LLM_API_KEY")
        )
        
        self.prompt_template = """
        用户输入的问题：{question}
        系统推荐了以下课程：
        {context}
        请根据我的问题，从系统推荐的课程中，选择最合适我的课程，并给我充分的理由。        
        """
    
    
    def generate_recommendation(self, 
                              question: str, 
                              similar_courses: List[Dict[str, Any]]) -> Dict[str, Any]:
            # 构造上下文
        context = "\n".join([
            f"课程：{course.get('name', '未知课程')}\n"
            f"描述：{course.get('description', '暂无描述')}\n"
            f"年级：{course.get('grade_level', '未知')}\n"
            f"学科：{course.get('subject', '未知')}\n"
            f"难度：{course.get('difficulty', '未知')}\n"
            for course in similar_courses
        ])
        # 构造完整提示
        prompt = self.prompt_template.format(
            context=context,
            question=question
        )
        # 调用LLM生成推荐
        response = self.client.chat.completions.create(
            model=os.getenv("LLM_MODEL_NAME"),
            messages=[
                {"role": "system", "content": "你是一个专业的课程推荐助手。"},
                {"role": "user", "content": prompt}
            ],
            temperature=0.7
        )


        result = response.choices[0].message.content
        return result
            
    
    def process_query(self, 
                     question: str, 
                     db_manager: Any, 
                     ) -> Dict[str, Any]:
        # 获取相似课程
        similar_courses = db_manager.search_similar_courses(question)
        # 生成推荐
        recommendation = self.generate_recommendation(question, similar_courses)
        return {
            "similar_courses": similar_courses,
            "recommendation": recommendation
        } 